<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Email_reader
 *
 * @author Juraj
 */
class Email_reader {

    public $conn;
    private $inbox;
    private $msg_cnt;
    private $server;
    private $user;
    private $pass;
    private $port; // adjust according to server settings

    function __construct($server, $user, $pass, $port = 143) {
        $this->server = $server;
        $this->user = $user;
        $this->pass = $pass;
        $this->port = $port;
        $this->connect();
    }

    function close() {
        $this->inbox = array();
        $this->msg_cnt = 0;
        imap_close($this->conn);
    }

    function connect() {
        $this->conn = imap_open('{' . $this->server . '/notls}', $this->user, $this->pass);
    }

    function inbox($criteria = null) {
        if (empty($criteria)) {
            $criteria = 'ALL';
        }

        $uids = imap_sort($this->conn, SORTDATE, 1, 0, $criteria);
        //$uids   = imap_search($this->conn, $criteria);//

        $in = array();
        foreach ($uids as $i) {
            $temp_in = array(
                'index' => $i,
                'header' => imap_headerinfo($this->conn, $i),
                'body' => imap_fetchbody($this->conn, $i, 1.2),
                'structure' => imap_fetchstructure($this->conn, $i)
            );

            if (!strlen($temp_in['body']) > 0) {
                $temp_in['body'] = imap_fetchbody($this->conn, $i, 1);
            }
            
            $in[] = $temp_in;
        }

        $this->inbox = $in;

        return $this->inbox;
    }

}
?>

